﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using RestSharp;

namespace EvertonApp.AdminWeb.Controllers.Proxy
{
    public class ProxyHelper
    {
        private const string BaseUrl = "http://localhost:8080";

        readonly string _accountSid;
        readonly string _secretKey;

        public static IRestResponse Execute(RestRequest request)
        {
            var client = new RestSharp.RestClient();
            client.BaseUrl = BaseUrl;

            var response = client.Execute(request);

            //Para usar cuando implementemos la autentificación
            //client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            //request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                throw new ApplicationException(message, response.ErrorException);
            }

            return response;

        }

        public static T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestSharp.RestClient();
            client.BaseUrl = BaseUrl;

            //Para usar cuando implementemos la autentificación
            //client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            //request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request

            var response = client.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                throw new ApplicationException(message, response.ErrorException);
            }

            return response.Data;
        }

        public static List<T> ExecuteList<T>(RestRequest request) where T : new()
        {
            var client = new RestSharp.RestClient();
            client.BaseUrl = BaseUrl;


            //Para usar cuando implementemos la autentificación
            //client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
            //request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request

            var response = client.Execute<T>(request);

            List<T> myResults;

            using (Stream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
            {
                myResults = JsonConvert.DeserializeObject<List<T>>(new StreamReader(ms2).ReadToEnd());
            }

            return myResults;
        }
    }
}